var Host = (function() {

  /*定义常用变量*/
  var cases = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
  var colors = ['#4572a7', '#aa4643', '#89a54e', '#e2f1dc', '#4572a7', '#aa4643', '#e2f1dc'];

  var idata = {};
  var chart = {};
  var val = [0, 0, 0, 0, 0, 0, 0];
  /*图表投票选项数据类*/
  function Chioce(name, value, color) {
    this.name = name;
    this.value = value;
    this.color = colors[color];
  }

  /*图标配置对象类*/
  function Item(title, choices, data) {
    this.title = title;
    this.choices = new Array();
    for (var i = 0; i < choices.length; i++) {
      this.choices[i] = new Chioce(choices[i], val[i], i);
    }
    this.userAry = new Array();
  }

  /*更新投票选项数据*/
  Item.prototype.choiceUpdate = function(value) {
    for (var i = 0; i < this.choices.length; i++) {
      this.choices[i] = new Chioce(this.choices[i].name, value[i], i);
    }
    drawChart();
  }

  var newDialog = function() {
      $('#start-box').modal('show');
  }
  /*创建图标配置对象*/
  var newItem = function() {
    var title = $('input[name="title"]').val();
    if (title == '') {
      $('input[name="title"]').placeholder = '必须输入主题';
      return;
    }
    var choices = new Array();
    var tmpStr = '';
    for (var i = 0; i < $('.choice-input').length; i++) {
      if ($('.choice-input:eq(' + i + ')').val() != '') {
        choices.push($('.choice-input:eq(' + i + ')').val());
        tmpStr += '<li>' + $('.choice-input:eq(' + i + ')').val() + '</li>';
      };
    }
    if (!choices.length) {
      alert('必须添加至少一个选项');
      return;
    }
    /*更改界面元素*/
    $('#new-item-btn').html('重新发起投票');
    $('#item-title').html(title);
    $('#item-list').html(tmpStr);
    /*绘制图表*/
    val = [0, 0, 0, 0, 0, 0, 0];
    idata = new Item(title, choices, idata);
    drawChart();
  }

  /*视图添加选择项目*/
  var addChioce = function() {
      $count = $('.choice-label').length;
      if ($count >= 7) {
        alert('已到达选项的上限');
        return;
      }
      $group = $('<div/>');
      $group.addClass('form-group').addClass('item-group');
      $label = $('<label/>', {
        'for': 'choice' + $count,
      }).appendTo($group);
      $input = $('<input/>', {
        'name': 'choice' + $count,
        'type': 'text',
        'maxlength': '12',
        'placeholder': '请不要留空',
      }).appendTo($group);
      $label.addClass('col-md-2');
      $label.addClass('control-label');
      $label.addClass('choice-label');
      $label.text('选项' + cases[$count] + '：');
      $input.addClass('choice-input');
      $('#details-form').append($group);
      $input.focus();
    }
    /*删除选项*/
  var delChioce = function() {
      var items = $('.item-group');
      if (!items.length) {
        return;
      };
      var length = items.length;
      var last = items[length - 1];
      last.remove();
    }
    /*重新绘图*/
  var drawChart = function() {
      chart = newChart();
      chart.draw();
    }
    /*创建图表对象*/
  var newChart = function() {
      var maxNum = idata.choices[0].value
      for (var i = 1; i < idata.choices.length; i++) {
        if (idata.choices[i].value > maxNum) {
          maxNum = idata.choices[i].value;
        }
      }
      return new iChart.Column2D({
        render: 'canvasDiv',
        data: idata.choices,
        title: {
          text: idata.title,
          color: '#3e576f'
        },
        subtitle: {
          text: idata.subTitle,
          color: '#6d869f'
        },
        footnote: {
          text: '投票系统',
          color: '#909090',
          fontsize: 11,
          padding: '0 38'
        },
        width: 710,
        height: 360,
        label: {
          fontsize: 11,
          color: '#666666'
        },
        animation: true, //开启过渡动画
        animation_duration: 800, //800ms完成动画
        shadow: true,
        shadow_blur: 2,
        shadow_color: '#aaaaaa',
        shadow_offsetx: 1,
        shadow_offsety: 0,
        column_width: 62,
        sub_option: {
          listeners: {
            parseText: function(r, t) {
              return t + "人";
            }
          },
          label: {
            fontsize: 11,
            fontweight: 600,
            color: '#4572a7'
          },
          border: {
            width: 2,
            color: '#ffffff'
          }
        },
        coordinate: {
          background_color: null,
          grid_color: '#c0c0c0',
          width: 640,
          axis: {
            color: '#c0d0e0',
            width: [0, 0, 1, 0]
          },
          scale: [{
            position: 'left',
            start_scale: 0,
            end_scale: maxNum > 6 ? maxNum : 6,
            scale_space: parseInt(maxNum / 6) > 1 ? parseInt(maxNum / 6) : 1,
            scale_enable: false,
            label: {
              fontsize: 11,
              color: '#666666'
            }
          }]
        }
      });
    }

    // node modules
  var os = require('os');
  var exec = require('child_process').exec;

  // my modules
  var server = require('../controller/server');
  // get ip address and draw a qrcode
  function drawAddress() {
    var ipInstruct = '';
    if (os.platform() != 'win32') {
      ipInstruct = 'ifconfig';
    } else {
      ipInstruct = 'ipconfig';
    }
    exec(ipInstruct, function(error, stdout, stderr) {
      if (error) {
        console.log(error);
      } else {
        if (stdout.match(/(192.168.[0-9]*.[0-9]*)/)) {
          var url = 'http://' + stdout.match(/(192.168.[0-9]*.[0-9]*)/).pop() + ':3000';
          new QRCode(document.getElementById("qrcode"), url);
          document.getElementById("qrcode").style.display = 'none';
          //$('#header-title').text($('#header-title').text() + '(服务器IP：' + url + ')');
        }
      }
    });
  }

  function startServer() {
    var connectcb = function(clients) {
      $('#stats-clients').text(clients.length);
    }
    var updatecb = function(data, extra) {
      var msg = $.parseJSON(data);
      var dom = '<section class="timeline-item">' +
        '<div class="timeline-tail">' +
        '<div class="timeline-node"></div>' +
        '</div>' +
        '<div class="timeline-content">' +
        '<p class="timeline-header">' +
        '<span class="timeline-author">' + msg.name + '</span>&nbsp;&nbsp;' +
        '<span class="timeline-timestamp">' + msg.time + '</span>' +
        '</p>' +
        '<p class="timeline-text">' + msg.text + '</p>' +
        '</div>' +
        '</section>';
      var tmp = parseInt(msg.text);
      if (tmp <= idata.choices.length && tmp > 0) {
        var flag = true;
        for (var j = 0; j < idata.userAry.length; j++) {
          if (idata.userAry[j] === msg.name) {
            break;
          }
        }
        if (j === idata.userAry.length && flag) {
          val[tmp - 1] ++;
          idata.choiceUpdate(val);
          idata.userAry.push(msg.name);
        } 
      }
      $(dom).addClass('animated').addClass('fadeIn').appendTo('#chat-in-box');
      domCallback();
      statUpdate(extra);
    }
    server.start(connectcb, updatecb);
  }

  function domCallback() {
    var items = $('.timeline-item');
    var length = items.length;
    var last = items[length - 1];
    var marginTop = parseInt($(last).css('margin-top').substring(-2));
    var curHeight = $('.timeline-background').height();
    var curMargin = parseInt($('.timeline-end').css('margin-top').substring(-2));
    var incHeight = $(last).height() + marginTop;
    $('.timeline-background').height(curHeight + incHeight);
    $('.timeline-end').css('margin-top', curMargin + incHeight + 'px');
    var chatBox = document.getElementById('chat-in-box');
    var sheight = chatBox.scrollHeight;
    $('.chat-box').animate({
      scrollTop: (sheight - 14)
    }, 1500);
  }

  function statUpdate(data) {
    $('#stats-msgCount').text(data);
  }

  // dom thingy
  $(document).on('ready', function() {
    $('#main').height($('body')[0].scrollHeight - $('.navbar')[0].scrollHeight - 16);
    drawAddress();
    startServer();
  });

  $('#new-item-btn').on('click', function() {
    newDialog();
  });
  $('#add-choice').on('click', function() {
    addChioce();
  });
  $('#ndel-choice').on('click', function() {
    delChioce();
  });
  $('#ensureNew').on('click', function() {
    newItem();
  });
  $('#qrcode-btn').on('click', function() {
    $('#qrcode').fadeToggle(800);
    if ($('#qrcode-btn').html() === '查看二维码') {
      $('#qrcode-btn').html('关闭二维码');
      $('#qrcode-btn').removeClass('btn-primary').addClass('btn-warning');
    } else {
      $('#qrcode-btn').html('查看二维码');
      $('#qrcode-btn').removeClass('btn-warning').addClass('btn-primary');
    }
  });

  return {

  }

})();